import React, { useEffect, useState } from 'react';
import { Tooltip } from 'antd';
import styles from './index.less';

const defaultColor = [
    '#FF8C00',
    '#FF4D4F',
    '#FF7A45',
    '#FFC53D',
    '#FFEC3D',
    '#BAE637',
    '#73D13D',
    '#36CFC9',
    '#40A9FF',
    '#597EF7',
    '#9254DE',
    '#F759AB',
    '#F5222D',
    '#389E0D',
    '#096DD9',
    '#531DAB',
    '#AD4E00',
    '#08979C'
];

// 判断是否为十六进制颜色值
const isHexColor = color => {
    const regex = /^#[0-9A-Fa-f]{6,8}$/;
    if (regex.test(color)) {
        return true;
    }
    return false;
};

// 16进制颜色转RGBA
const hexToRgba = (hexColor, opacity = 1) => {
    let hex = '';

    if (isHexColor(hexColor)) {
        hex = hexColor.substring(1);
    }

    return `rgba(${parseInt(`0x${hex.slice(1, 3)}`, 16)},${parseInt(`0x${hex.slice(3, 5)}`, 16)},${parseInt(
        `0x${hex.slice(5, 7)}`,
        16
    )},${opacity})`;
};

// 随机生成十六进制颜色
const generateColors = count => {
    const colors = new Set();
    while (colors.size < count) {
        const color = `#${`${Math.random().toString(16)}00000000`.substring(2, 8)}`;
        colors.add(color);
    }
    return [...colors];
};

const getIgnoreColors = selectColors => {
    if (!Array.isArray(selectColors)) {
        return [];
    }
    return selectColors.map(item => item.colorCode);
};

const getOrganizationNameByColor = (selectColors, color) => {
    if (!Array.isArray(selectColors)) {
        return '';
    }
    return selectColors.find(item => item.colorCode === color)?.organizationName;
};

const filterColors = colors => {
    const result = colors.filter(item => isHexColor(item));
    return result;
};

const NUMBER_OF_COLORS = 18;

const Colors = React.forwardRef(({ value, onChange, auto, colors, ignoreColors }, ref) => {
    const [colorList, setColorList] = useState(filterColors(defaultColor));
    const [selectColor, setSelectColor] = useState('');
    const cannotSelected = getIgnoreColors(ignoreColors);

    useEffect(() => {
        setSelectColor(value);
    }, [value]);

    useEffect(() => {
        if (auto) {
            const result = generateColors(NUMBER_OF_COLORS);
            setColorList(result);
        } else if (colors && Array.isArray(colors)) {
            const result = filterColors(colors);
            setColorList(result);
        }
    }, [auto, colors]);

    const isCannotSelected = (color = '') => cannotSelected.includes(color.toUpperCase());

    const handleClick = color => {
        const isDisabled = isCannotSelected(color);
        if (isDisabled) {
            return;
        }

        setSelectColor(color);
        if (onChange) {
            onChange(color);
        }
    };

    return (
        <div className={styles.colorPickerWrapper} ref={ref}>
            {colorList.map(color => (
                <div key={color} className={styles.colorBox}>
                    <Tooltip title={getOrganizationNameByColor(ignoreColors, color)}>
                        <span
                            className={`${selectColor === color ? styles.action : ''} ${
                                isCannotSelected(color) ? styles.cannotSelected : ''
                            }`}
                            style={{
                                borderColor: isCannotSelected(color) ? 'transparent' : color,
                                color: isCannotSelected(color) ? color : 'white'
                            }}
                            onClick={() => handleClick(color)}
                        >
                            <span
                                className={styles.innerCircle}
                                style={{
                                    backgroundColor: isCannotSelected(color) ? hexToRgba(color, 0.2) : color
                                }}
                            ></span>
                        </span>
                    </Tooltip>
                </div>
            ))}
        </div>
    );
});

export default Colors;
